// AVCapDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AVCap.h"
#include "AVCapDlg.h"

#include "CVideoSourcePage.h"
#include "CAudioSourcePage.h"
#include "COutputPage.h"
#include "GlobalDefs.h"
#include "CVideoDevices.h"
#include "CAudioDevices.h"

#include "CGraphController.h"
#include "CCaptureController.h"
#include "CPreviewController.h"
#include "CLiveInputFilters.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAVCapDlg dialog

CAVCapDlg::CAVCapDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAVCapDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CAVCapDlg)
	mOutputFile = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	mController = NULL;
	mLiveCapture.AddMsgReceiver(this);
	CVideoDevices::Instance()->AddMsgReceiver(this);
}

void CAVCapDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAVCapDlg)
	DDX_Control(pDX, IDC_EDIT_SAVE_FILE, mEditSaveFile);
	DDX_Control(pDX, IDC_BUTTON_GRAB, mButtonGrab);
	DDX_Control(pDX, IDC_BUTTON_ADVANCED_VIDEO, mButtonVideoSettings);
	DDX_Control(pDX, IDC_BUTTON_ADVANCED_OUTPUT, mButtonOutputSettings);
	DDX_Control(pDX, IDC_BUTTON_ADVANCED_AUDIO, mButtonAudioSettings);
	DDX_Control(pDX, IDC_BUTTON_CAPTURE, mButtonCapture);
	DDX_Control(pDX, IDC_VIDEO_WINDOW, mVideoWindow);
	DDX_Control(pDX, IDC_COMBO_DEVICE_AUDIO, mComboAudioDevices);
	DDX_Control(pDX, IDC_COMBO_DEVICE_VIDEO, mComboVideoDevices);
	DDX_Text(pDX, IDC_EDIT_SAVE_FILE, mOutputFile);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAVCapDlg, CDialog)
	//{{AFX_MSG_MAP(CAVCapDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_ERASEBKGND()
	ON_BN_CLICKED(IDC_BUTTON_ADVANCED_VIDEO, OnButtonAdvancedVideo)
	ON_BN_CLICKED(IDC_BUTTON_ADVANCED_AUDIO, OnButtonAdvancedAudio)
	ON_BN_CLICKED(IDC_BUTTON_ADVANCED_OUTPUT, OnButtonAdvancedOutput)
	ON_WM_DESTROY()
	ON_CBN_SELCHANGE(IDC_COMBO_DEVICE_AUDIO, OnSelchangeComboDeviceAudio)
	ON_CBN_SELCHANGE(IDC_COMBO_DEVICE_VIDEO, OnSelchangeComboDeviceVideo)
	ON_BN_CLICKED(IDC_BUTTON_CAPTURE, OnButtonCapture)
	ON_BN_CLICKED(IDC_BUTTON_GRAB, OnButtonGrab)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAVCapDlg message handlers

BOOL CAVCapDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	mLiveCapture.SetNotifying(FALSE);
	
	FillAudioDevices();
	FillVideoDevices();
	mOutputFile = mLiveCapture.GetOutputFile();
	UpdateData(FALSE);

	CreateController();

	mLiveCapture.SetNotifying(TRUE);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CAVCapDlg::OnDestroy() 
{
	if (mController)
	{
		mController->Deactive();
		delete mController;
		mController = NULL;
	}

	CVideoDevices::Release();
	CAudioDevices::Release();

	CDialog::OnDestroy();
}


// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAVCapDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAVCapDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

BOOL CAVCapDlg::OnEraseBkgnd(CDC* pDC)
{
	// Intercept background erasing for the movie window, since the
	// video renderer will keep the screen painted.  Without this code,
	// your video window might get painted over with gray (the default
	// background brush) when it is obscured by another window and redrawn.
	CRect rc;
	// Get the bounding rectangle for the movie screen
	mVideoWindow.GetWindowRect(&rc);
	ScreenToClient(&rc);
	// Exclude the clipping region occupied by our movie screen
	pDC->ExcludeClipRect(&rc);

	// Erase the remainder of the dialog as usual
	return CDialog::OnEraseBkgnd(pDC);
}

void CAVCapDlg::CreateController(void)
{
	SAFE_DELETE(mController);
	
	switch (mLiveCapture.GetWorkMode())
	{
	case MD_Capture:
		mController = new CCaptureController();
		break;

	case MD_Preview:
	default:
		mController = new CPreviewController();
		break;
	}

	// Settings...
	mController->SetVideoWindow(&mVideoWindow);
	mController->SetLiveCapture(&mLiveCapture);
	mController->Activate();
}

void CAVCapDlg::FillAudioDevices(void)
{
	mComboAudioDevices.ResetContent();

	POSITION pos = CAudioDevices::Instance()->mList.GetHeadPosition();
	while (pos)
	{
		CDSDevice device = CAudioDevices::Instance()->mList.GetNext(pos);
		mComboAudioDevices.AddString(device.GetDeviceFriendlyName());
	}

	// Select the first device
	if (mComboAudioDevices.GetCount() > 0)
	{
		mComboAudioDevices.SetCurSel(0);
		CString deviceName;
		mComboAudioDevices.GetLBText(0, deviceName);
		mLiveCapture.SetAudioDevice(deviceName);
	}
}

void CAVCapDlg::FillVideoDevices(void)
{
	mComboVideoDevices.ResetContent();

	POSITION pos = CVideoDevices::Instance()->mList.GetHeadPosition();
	while (pos)
	{
		CDSDevice device = CVideoDevices::Instance()->mList.GetNext(pos);
		mComboVideoDevices.AddString(device.GetDeviceFriendlyName());
	}
	
	// Select the first device 
	if (mComboVideoDevices.GetCount() > 0)
	{
		mComboVideoDevices.SetCurSel(0);
		CString deviceName;
		mComboVideoDevices.GetLBText(0, deviceName);
		mLiveCapture.SetVideoDevice(deviceName);
	}
}

bool CAVCapDlg::ReceiveMessage(MessageT inMessage, 
							   void * ioParam,
							   void * ioParam2)
{
	switch (inMessage)
	{
	case msg_PnPDeviceAdded:
		FillVideoDevices();
		return true;

	case msg_PnPDeviceRemoved:
		FillVideoDevices();
		return true;
	}

	return CMsgReceiver::ReceiveMessage(inMessage, ioParam, ioParam2);
}

bool CAVCapDlg::Respond(NotifyT inNotification, CMsgStation * inStation,
						long inParam1, long inParam2)
{
	switch (inNotification)
	{
	case cVideoSourceChanged: // Reset filter graph
		CreateController();
		return true;

	case cAudioSourceChanged: // Reset filter graph
		CreateController();
		return true;

	case cVideoConnectorChanged:
		EnterVideoConnector();
		return true;

	case cAudioConnectorChanged:
		EnterAudioConnector();
		return true;

	case cAudioMixLevelChanged:
		EnterAudioMixLevel();
		return true;

	case cVideoResolutionChanged:
		// Rebuild the filter graph, or preview will be disordered
		if (mController)
		{
			mController->Deactive();
			mController->Activate();
		}
		return true;
	}

	return CMsgReceiver::Respond(inNotification, inStation, inParam1, inParam2);
}

void CAVCapDlg::OnButtonAdvancedVideo() 
{
	if (mController)
	{
		CVideoSourcePage  dlg;
		dlg.SetLiveCapture(&mLiveCapture);
		dlg.SetInputFilters(mController->GetInputFilters());
		dlg.DoModal();
	}
}

void CAVCapDlg::OnButtonAdvancedAudio() 
{
	if (mController)
	{
		CAudioSourcePage  dlg;
		dlg.SetLiveCapture(&mLiveCapture);
		dlg.SetInputFilters(mController->GetInputFilters());
		dlg.DoModal();
	}
}

void CAVCapDlg::OnButtonAdvancedOutput() 
{
	COutputPage   dlg;
	dlg.SetLiveCapture(&mLiveCapture);
	dlg.DoModal();
}

void CAVCapDlg::EnterVideoConnector(void)
{
	if (mController && mController->GetInputFilters())
	{
		long connector = mLiveCapture.GetVideoConnector();
		mController->GetInputFilters()->SetVideoConnector(connector);
	}
}

void CAVCapDlg::EnterAudioConnector(void)
{
	if (mController && mController->GetInputFilters())
	{
		long connector = mLiveCapture.GetAudioConnector();
		mController->GetInputFilters()->SetAudioConnector(connector);
	}
}

void CAVCapDlg::EnterAudioMixLevel(void)
{
	if (mController && mController->GetInputFilters())
	{
		double level = mLiveCapture.GetAudioMixLevel();
		mController->GetInputFilters()->SetAudioMixLevel(level);
	}
}

// Select one audio device
void CAVCapDlg::OnSelchangeComboDeviceAudio() 
{
	int index = mComboAudioDevices.GetCurSel();
	if (index != CB_ERR)
	{
		CString deviceName;
		mComboAudioDevices.GetLBText(index, deviceName);
		mLiveCapture.SetAudioDevice(deviceName);
	}
}

// Select one video device
void CAVCapDlg::OnSelchangeComboDeviceVideo() 
{
	int index = mComboVideoDevices.GetCurSel();
	if (index != CB_ERR)
	{
		CString deviceName;
		mComboVideoDevices.GetLBText(index, deviceName);
		mLiveCapture.SetVideoDevice(deviceName);
	}
}

// Begin capture audio/video to file
void CAVCapDlg::OnButtonCapture() 
{
	if (mLiveCapture.GetWorkMode() == MD_Preview)
	{
		UpdateData(TRUE);
		mLiveCapture.SetOutputFile(mOutputFile);

		// From preview mode to capture mode
		mLiveCapture.SetWorkMode(MD_Capture);
		mButtonCapture.SetWindowText("Stop");
		UpdateControls(FALSE);
	}
	else
	{
		// From capture mode to preview mode
		mLiveCapture.SetWorkMode(MD_Preview);
		mButtonCapture.SetWindowText("Capture");
		UpdateControls(TRUE);
	}

	// Re-build the filter graph
	CreateController();
}

// Grab the current image and save as a bitmap file
void CAVCapDlg::OnButtonGrab() 
{
	if (mController)
	{
		CTime    currentTime = CTime::GetCurrentTime();
		CString  filename;
		filename.Format("%shq%02d-%02d-%02d.bmp", mLiveCapture.GetGrabFolder(),
			currentTime.GetHour(), currentTime.GetMinute(), currentTime.GetSecond());

		if (mController->SnapshotToFile(filename))
		{
			AfxMessageBox("Grab to "+filename+" succeeded!");
		}
		else
		{
			AfxMessageBox("Failed to capture a frame!");
		}
	}
}

void CAVCapDlg::UpdateControls(BOOL inEnable)
{
	mComboVideoDevices.EnableWindow(inEnable);
	mComboAudioDevices.EnableWindow(inEnable);
	mEditSaveFile.EnableWindow(inEnable);
	mButtonGrab.EnableWindow(inEnable);
	mButtonVideoSettings.EnableWindow(inEnable);
	mButtonOutputSettings.EnableWindow(inEnable);
	mButtonAudioSettings.EnableWindow(inEnable);
}
